#!/bin/sh
export KSROOT=/koolshare
source $KSROOT/scripts/base.sh
eval $(dbus export baidu_ddns_)
alias echo_date='echo 【$(date +%Y年%m月%d日\ %X)】\n'

log() {
  echo "【$(date +%Y年%m月%d日\ %X)】:" >$KSROOT/baidu_ddns/log.log
  echo "$@" >>$KSROOT/baidu_ddns/log.log
}

start_baidu_ddns() {
  if [ 0 == "$baidu_ddns_basic_enable" ] || [ "0" == "$baidu_ddns_basic_enable" ]; then
    log "系统未启用"
    return
  fi
  log "检测中。。。稍后。。。"
  sed -i '/baidu_ddns_check/d' /etc/crontabs/root >/dev/null 2>&1
  echo "*/$baidu_ddns_check * * * * /koolshare/scripts/baidu_ddns_config.sh check #baidu_ddns_check#" >>/etc/crontabs/root
  echo_date "设置百度DDNS自动检测，检测间隔 $baidu_ddns_check 分钟"
  check_cron
  check_pub_ip
}

stop_baidu_ddns() {
  sed -i '/baidu_ddns_check/d' /etc/crontabs/root >/dev/null 2>&1
  echo '' >$KSROOT/baidu_ddns/ip.txt
  echo_date "已停止百度DDNS"
  check_cron
}

check_pub_ip() {
  if [ -z "$baidu_ddns_access_key" ] || [ -z "$baidu_ddns_secret_key" ] || [ -z "$baidu_ddns_domain" ]; then
    echo_data "参数未设置，无法运行"
    log "参数未设置，无法运行"
    stop_baidu_ddns
    return 0
  fi
  echo_date "开始检测外网IP...."
  old_pub_ip=$(cat $KSROOT/baidu_ddns/ip.txt)
  pub_ip=$(curl whatismyip.akamai.com)
  if [ "$old_pub_ip" == "$pub_ip" ]; then
    echo_date "已获取外网IP $pub_ip 且没有变化"
    log "已获取外网IP $pub_ip 且没有变化"
  else
    echo_date "已获取外网IP $pub_ip ，与原有IP不同，进行解析更新"
    exec_baidu_ddns
  fi
}

exec_baidu_ddns() {
  result=$($KSROOT/bin/baidu_ddns -ak=$baidu_ddns_access_key -sk=$baidu_ddns_secret_key -domain=$baidu_ddns_domain)
  echo $result >$KSROOT/baidu_ddns/ip.txt
  if [ "$result" == "" ]; then
    log "解析失败，请稍后再试或等待下次检测"
  else
    log "解析成功，已经将 $baidu_ddns_domain 解析到 $result ，大概五分钟左右生效"
  fi
}

check_cron() {
  local crontab
  crontab=$(pidof crond)
  [ -z "$crontab" ] && /etc/init.d/cron start >/dev/null 2>&1
}

# used by rc.d
case $1 in
start)
  start_baidu_ddns
  ;;
stop)
  stop_baidu_ddns
  ;;
check)
  check_pub_ip
  ;;
exec)
  exec_baidu_ddns
  ;;
*) ;;

esac

# used by httpdb
case $2 in
save)
  stop_baidu_ddns
  http_response "设置已保存！"
  start_baidu_ddns
  ;;
log)
  http_response $(cat $KSROOT/baidu_ddns/log.log)
  ;;
esac
